#include<sys/epoll.h>
#include<unistd.h>
#include"Log.hpp"
#include<string.h>
#include<errno.h>
#include<set>
class Epoller
{
public:
    const static int defaultepfd = -1;
    const static int size = 128;
    Epoller() : _epfd(defaultepfd)
    {
    }
    void InitEpoller()
    {
        _epfd = epoll_create(size);
        if (_epfd == defaultepfd)
        {
            lg.LogMessage(Fatal, "create_epoll error,%s : %d\n", strerror(errno), errno);
            exit(4);
        }
        lg.LogMessage(Info, "create_epoll success,%d\n", _epfd);
    }
    void Add(int sockfd, uint32_t event)
    {
        fd_list.insert(sockfd);
        struct epoll_event ev;
        ev.events = event;
        ev.data.fd = sockfd;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
        if (n < 0)
        {
            lg.LogMessage(Error, "epoll_ctl add error,%s : %d\n", strerror(errno), errno);
        }
        lg.LogMessage(Info, "epoll_ctl add success\n");
    }
    void MOD(int scokfd,uint32_t event)
    {
        struct epoll_event ev;
        ev.events = event;
        ev.data.fd = scokfd;
        int n = epoll_ctl(_epfd, EPOLL_CTL_MOD, scokfd, &ev);
        if (n < 0)
        {
            lg.LogMessage(Error, "epoll_ctl add error,%s : %d\n", strerror(errno), errno);
        }
        lg.LogMessage(Info, "epoll_ctl add success\n");
    }
    int Wait(struct epoll_event *ev, int maxevents, int timeout)
    {
        int n = epoll_wait(_epfd, ev, maxevents, timeout);
        return n;
    }
    void DelEvent(int sockfd)
    {
        fd_list.erase(sockfd);
        epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
    }
    void PrintList()
    {
        std::cout<<"connect fd_list is: ";
        for(auto& e:fd_list)
        {
            std::cout<<e<<" ";
        }
        std::cout<<std::endl;
    }
    ~Epoller()
    {
        if (_epfd >= 0)
        {
            close(_epfd);
            lg.LogMessage(Info, "epoll close success,%d\n", _epfd);
        }
    }

private:
    int _epfd;
    std::set<int> fd_list;
};
